package com.pig4cloud.pig.demo.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.annotation.Inner;
import com.pig4cloud.pig.demo.Service.ArticleService;
import com.pig4cloud.pig.demo.Service.UserService;
import com.pig4cloud.pig.demo.Util.ArticleContentProcessor;
import com.pig4cloud.pig.demo.Util.TokenUtils;
import com.pig4cloud.pig.demo.feign.Entity.Article;
import com.pig4cloud.pig.demo.feign.Entity.Company;
import com.pig4cloud.pig.demo.feign.Entity.User;
import com.pig4cloud.pig.demo.feign.vo.MyArticleVO;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

@Inner
@RestController
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @Autowired
    private UserService userService;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ArticleContentProcessor articleContentProcessor;

    @GetMapping("/article/pagingQuery/{category}")
    public R pagingQuery(@PathVariable String category) throws IOException {
        //得到当前文章分类数量
        long categoryCount = articleService.findCategoryCount(category);
        //System.out.println(categoryCount);
        if (categoryCount == 0) {
            //当前文章分类数量为0，爬取文章
            articleContentProcessor.process(category);
        }

        List<Map<String, Object>> maps = articleService.pagingQuery(category, 0, 5);

        return R.ok(maps);
    }

    @GetMapping("/article/findArticleContentById/{id}")
    public R findArticleContentById(@PathVariable Long id) throws IOException {
        String content = articleService.findArticleContentById(id);
        if (content == null)
            return R.failed();
        return R.ok(content);
    }

    @GetMapping("/article/searchByKeyword/{keyword}")
    public R searchByKeyword(@PathVariable String keyword) throws IOException {
        List<Map<String, Object>> maps = articleService.searchByKeyword(keyword);
        if (maps != null && maps.size() != 0) {
            return R.ok(maps);
        }
        return R.failed();
    }

    @Value("${article.index}")
    private String esIndex;

    /**
     * 根据文章分类查找文章
     */
    @Inner(value = false)
    @PostMapping("article/es/getArticleByType")
    public R getArticleByType(@RequestBody HashMap<String, String> map1){
        String category = map1.get("category");

        SearchRequest searchRequest = new SearchRequest(esIndex);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //设置分页
        sourceBuilder.from(0);
        sourceBuilder.size(6);


        MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("category", category.toLowerCase());
        sourceBuilder.query(matchQuery);
        //sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //执行搜索
        searchRequest.source(sourceBuilder);

        SearchResponse search = null;
        try {
            search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Map<String, Object> map = new HashMap<>(4);

        if (search == null) {
            map.put("total", 0);
            map.put("records", null);
            return R.ok(map);
        }
        SearchHits searchHits = search.getHits();
        //查询总条数
        long value = searchHits.getTotalHits().value;

        //解析结果
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit documentFields : searchHits.getHits()) {
            list.add(documentFields.getSourceAsMap());
        }

        map.put("total", value);
        map.put("records", list);
        return R.ok(map);

    }

    /**
     * 保存或修改文章
     * @param article
     * @return
     */
    @Inner(value = false)
    @PostMapping("/article/save")
    public R saveArticle(@RequestBody Article article, HttpServletRequest request){
        //通过tooken获取用户id
        Long id = TokenUtils.getId(request);
        if (id == null) {
            return R.failed("用户id为空");
        }
        //设置默认价格
        if(article.getPrice()==null){
            article.setPrice(0f);
        }
        //设置默认图片
        if(article.getPicUrl()==null){
            article.setPicUrl("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1728577482,2585850803&fm=26&gp=0.jpg");
        }

        article.setUid(id);
        User user = userService.getById(id);
        if (user != null) {
            article.setPerson(user.getNickName());
        }
        //未审核
        article.setStatus(0);
        if(article.getId()==null){
            articleService.insertArticle(article);
        }
        article.setUpdateTime(new Date());
        articleService.updateById(article);
        return R.ok();
    }

    /**
     * 获取当前用户发布的文章
     * @return
     */
    @Inner(value = false)
    @GetMapping("/article/getMyArticle")
    public R getArticleByUserId(HttpServletRequest request){
        Long userId = TokenUtils.getId(request);
        if (userId == null) {
            return R.failed("用户id为空");
        }
        List<MyArticleVO> myArticleVOS = articleService.queryMyArticleVO(userId);

        return R.ok(myArticleVOS);
    }
}
